package fr.ul.ade.secunde.sync;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import fr.ul.ade.secunde.database.AdeWebContract;
import fr.ul.ade.secunde.util.AdeWebFactory;

/**
 * Classe responsable de la synchronisation de la liste des projets ADE.
 * 
 * @author Michaël Schnell
 * @since Aug 6, 2013
 * 
 * @version 1.3
 */
public class ProjectUpdateRunnable
		implements Runnable {

	private Context context;

	public ProjectUpdateRunnable(Context context) {
		this.context = context;
	}

	@Override
	public void run() {
		Log.d("[updateProjects]", "");

		try {
			// Initialisation de la connexion
			AdeWebInterface adeWebInterface = AdeWebFactory.establishConnection(this.context);
			// Lancement de la mise à jour
			final Cursor projects = adeWebInterface.getProjects();
			Log.d("[updateProjects]", "Found projects: " + projects.getCount());
			if (projects.getCount() > 0) {
				// Suppression des anciens projets
				Log.d("[updateProjects]", "Deleting old projects ...");
				this.context.getContentResolver().delete(AdeWebContract.Project.CONTENT_URI, null, null);
				// Ajout des nouveaux projets
				Log.d("[updateProjects]", "Inserting new projects ...");
				projects.moveToFirst();
				do {
					this.context.getContentResolver().insert(AdeWebContract.Project.CONTENT_URI, cursorToProjectValues(projects));
				} while (projects.moveToNext());
			}
			// Libération du curseur
			projects.close();
		} catch (Exception e) {
			Log.e("[updateProjects]", "Get projects failed !", e);
		}
		Log.d("[updateProjects]", "Finshed getting projects: ");
		// catch (IOException ioe) {
		// // FIXME Log and report exception !
		// } catch (NotFoundException nfe) {
		// // TODO: handle exception
		// } catch (XmlPullParserException xppe) {
		// // FIXME Log and report exception !
		// }
	}

	private static ContentValues cursorToProjectValues(final Cursor project) {
		final ContentValues values = new ContentValues();
		values.put(AdeWebContract.Project.PROJECT_ADEWEB_ID, Long.valueOf(project.getLong(ProjectQuery.PROJECT_ADEWEB_ID)));
		values.put(AdeWebContract.Project.PROJECT_NAME, project.getString(ProjectQuery.PROJECT_NAME));
		Integer loaded = Integer.valueOf(Boolean.parseBoolean(project.getString(ProjectQuery.PROJECT_LOADED)) ? 1 : 0);
		values.put(AdeWebContract.Project.PROJECT_LOADED, loaded);
		return values;
	}

}// class ScheduleUpdateRunnable